package com.wz.leetcode.linkedlist;

public class ReorderList_143 {
    public void reorderList(ListNode head) {
        if (head == null || head.next == null || head.next.next == null) {
            return;
        }
        ListNode mid = middleNode(head);
        // 奇数时，l1比l2长一个
        ListNode l1 = head;
        ListNode l2 = mid.next;
        mid.next = null;
        l2 = reverseList(l2);
        mergeList(l1, l2);
    }

    private void mergeList(ListNode l1, ListNode l2) {
        ListNode t1 = null;
        ListNode t2 = null;
        while(l1 != null && l2 != null) {
            t1 = l1.next;
            t2 = l2.next;
            l1.next = l2;
            l1 = t1;
            l2.next = l1;
            l2 = t2;
        }
    }

    private ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode cur = head;
        while(cur != null) {
            ListNode next = cur.next;
            cur.next = prev;
            prev = cur;
            cur = next;
        }
        return prev;
    }

    private ListNode middleNode(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        // 如果是3个，slow会指向中间那一个(012 -> 1)
        // 如果是4个，slow会指向中间两个的前一个（0123 -> 1）
        while (fast.next != null && fast.next.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        return slow;
    }
}
